const { app, BrowserWindow, ipcMain } = require('electron')
const { join } = require('path')
const { electronApp, optimizer, is } = require('@electron-toolkit/utils')
const { db, initializeDatabase } = require('./database')
const AppUpdater = require('./updater')
const log = require('electron-log')

// 初始化更新器
let appUpdater = null

// 创建主窗口
function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    show: false,
    autoHideMenuBar: true,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: true,
      enableRemoteModule: false,
      nodeIntegration: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    require('electron').shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // 根据环境加载页面
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// 应用准备就绪时执行
app.whenReady().then(async () => {
  // 设置应用用户模型 ID（Windows）
  electronApp.setAppUserModelId('top.bluelight.electron-vite-knex-sqlite3')

  // 开发环境下监听 F12 键
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // 初始化数据库
  try {
    await initializeDatabase()
    console.log('数据库初始化成功')
  } catch (error) {
    console.error('数据库初始化失败:', error)
    log.error('Database initialization failed:', error)
    
    // 显示错误对话框
    const { dialog } = require('electron')
    dialog.showErrorBox('数据库错误', 
      `数据库初始化失败，应用可能无法正常工作。

错误详情：${error.message}

请检查应用日志获取更多信息。`)
  }

  // 初始化更新器
  appUpdater = new AppUpdater()
  
  // 启动定期更新检查（生产环境）
  if (!is.dev) {
    appUpdater.startPeriodicCheck()
  }

  // 创建窗口
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// 关闭所有窗口时退出应用（macOS 除外）
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// IPC 处理程序 - 用户相关操作
ipcMain.handle('get-users', async () => {
  try {
    const users = await db('users').select('id', 'username', 'email', 'first_name', 'last_name', 'is_active', 'created_at')
    return { success: true, data: users }
  } catch (error) {
    console.error('Error fetching users:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('create-user', async (event, userData) => {
  try {
    const [userId] = await db('users').insert({
      username: userData.username,
      email: userData.email,
      password_hash: userData.password_hash,
      first_name: userData.first_name,
      last_name: userData.last_name
    }).returning('id')
    
    const user = await db('users').where('id', userId.id || userId).first()
    return { success: true, data: user }
  } catch (error) {
    console.error('Error creating user:', error)
    return { success: false, error: error.message }
  }
})

// IPC 处理程序 - 任务相关操作
ipcMain.handle('get-tasks', async (event, userId) => {
  try {
    let query = db('tasks')
      .leftJoin('users', 'tasks.user_id', 'users.id')
      .select(
        'tasks.*',
        'users.username',
        'users.first_name',
        'users.last_name'
      )
      .orderBy('tasks.created_at', 'desc')

    if (userId) {
      query = query.where('tasks.user_id', userId)
    }

    const tasks = await query
    return { success: true, data: tasks }
  } catch (error) {
    console.error('Error fetching tasks:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('create-task', async (event, taskData) => {
  try {
    // SQLite不支持RETURNING，需要分步操作
    const [taskId] = await db('tasks').insert({
      title: taskData.title,
      description: taskData.description,
      user_id: taskData.user_id,
      priority: taskData.priority || 'medium',
      due_date: taskData.due_date
    })
    
    // 获取刚插入的任务（taskId是插入行的rowid）
    const task = await db('tasks')
      .leftJoin('users', 'tasks.user_id', 'users.id')
      .select(
        'tasks.*',
        'users.username',
        'users.first_name',
        'users.last_name'
      )
      .where('tasks.id', taskId)
      .first()
      
    return { success: true, data: task }
  } catch (error) {
    console.error('Error creating task:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('update-task', async (event, taskId, updates) => {
  try {
    await db('tasks').where('id', taskId).update(updates)
    
    const task = await db('tasks')
      .leftJoin('users', 'tasks.user_id', 'users.id')
      .select(
        'tasks.*',
        'users.username',
        'users.first_name',
        'users.last_name'
      )
      .where('tasks.id', taskId)
      .first()
      
    return { success: true, data: task }
  } catch (error) {
    console.error('Error updating task:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('delete-task', async (event, taskId) => {
  try {
    await db('tasks').where('id', taskId).del()
    return { success: true }
  } catch (error) {
    console.error('Error deleting task:', error)
    return { success: false, error: error.message }
  }
})

// IPC 处理程序 - 更新相关操作
ipcMain.handle('check-for-updates', async () => {
  if (!appUpdater) {
    return { success: false, error: '更新器未初始化' }
  }
  
  try {
    const result = await appUpdater.manualCheck()
    return { success: true, data: result }
  } catch (error) {
    log.error('手动检查更新失败:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('download-update', async () => {
  if (!appUpdater) {
    return { success: false, error: '更新器未初始化' }
  }
  
  try {
    appUpdater.downloadUpdate()
    return { success: true }
  } catch (error) {
    log.error('下载更新失败:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('install-update', async () => {
  if (!appUpdater) {
    return { success: false, error: '更新器未初始化' }
  }
  
  try {
    appUpdater.quitAndInstall()
    return { success: true }
  } catch (error) {
    log.error('安装更新失败:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('get-update-status', async () => {
  if (!appUpdater) {
    return { success: false, error: '更新器未初始化' }
  }
  
  try {
    const status = appUpdater.getStatus()
    return { success: true, data: status }
  } catch (error) {
    log.error('获取更新状态失败:', error)
    return { success: false, error: error.message }
  }
})

// 应用退出时清理资源
app.on('before-quit', async () => {
  try {
    // 停止更新检查
    if (appUpdater) {
      appUpdater.stopPeriodicCheck()
    }
    
    // 关闭数据库连接
    await db.destroy()
    console.log('Database connection closed')
  } catch (error) {
    console.error('Error during cleanup:', error)
  }
})